package com.mocoop.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.mocoop.jfqc.R;
import com.mocoop.util.FileUtils;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
/**
 * 更新下载进度显示service
 * @author kevin
 */
public class UpdateNotifyService extends IntentService {

	private static final String TAG = "UpdateNotifyService";
	
	static final int HANDLER_LAODING = 0;

	static final int HANDLER_LOADED = 2;
	
	static final int HANDLER_FAILED = 4;

	static final int BUF_SIZE = 1024;
	
	private NotificationManager manager;
	private String url;
	private String fileName;
	private long size;
	private String downLoadPath;
	private Notification notification;
	private int iconId;
	
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			RemoteViews view = notification.contentView;
			switch (msg.what) {
			case HANDLER_LAODING:
				view.setProgressBar(R.id.progress, 100, msg.arg1, false);
				view.setTextViewText(R.id.update_text,"正在下载:"+msg.arg1+"%");
				manager.notify(iconId, notification);
				break;
			case HANDLER_LOADED:
				view.setTextViewText(R.id.update_text,"下载成功");
				manager.notify(iconId, notification);
				manager.cancel(iconId);
				sendLoadedState();
				break;
			case HANDLER_FAILED:
				view.setTextViewText(R.id.update_text,"下载失败");
				manager.notify(iconId, notification);
				break;
			}
		}
	};
	
	public UpdateNotifyService() {
		super("UpdateNotifyService");
	}

	@Override
	public void onCreate() {
		Log.v(TAG, "onCreate ...");
		manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		super.onCreate();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		Log.v(TAG, "onStart ...");
		url = intent.getStringExtra("url");
		fileName = intent.getStringExtra("fileName");
		size = intent.getLongExtra("size", 0);
		iconId = intent.getIntExtra("iconId", R.drawable.ic_launcher);
		File file = FileUtils.getExternalFile(this,"download",true);
		if(!file.exists()){
			file.mkdirs();
		}
		downLoadPath = file.toString()+File.separator+fileName;
		Log.v(TAG, "downpath="+downLoadPath+",url="+url);
		setUpNotification();
		super.onStart(intent, startId);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v(TAG, "onStartCommand ...");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {
		if (url == null) {
			mHandler.sendEmptyMessage(HANDLER_LOADED);
			return;
		}
		File file = new File(downLoadPath);
		
		InputStream in = null;
		FileOutputStream out = null;
		byte[] buf = new byte[BUF_SIZE];
		try {
			if (file.exists())
				file.delete();
			else
				file.createNewFile();
			if(url.startsWith("https")){
				disableSSLCertificateChecking();
			}
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			size = conn.getContentLength();
			Log.v(TAG, "size = "+size);
			in = conn.getInputStream();
			out = new FileOutputStream(downLoadPath);
			long count = 0;
			int progress = 0;
			int i;
			while ((i = in.read(buf)) != -1) {
				out.write(buf, 0, i);
				Log.v(TAG, "i = "+i);
				count += i;
				Log.v(TAG, "count = "+count);
				int temp_progress = (int)((count*100)/size);
				Log.v(TAG, "temp_progress = "+temp_progress);
				if(progress != temp_progress){
					progress = temp_progress;
					mHandler.sendMessage(mHandler.obtainMessage(HANDLER_LAODING, progress, 0));
				}
			}
		} catch (Exception e) {
			mHandler.sendEmptyMessage(HANDLER_FAILED);
			e.printStackTrace();
			return;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		mHandler.sendEmptyMessage(HANDLER_LOADED);
	}
	
	@SuppressWarnings("deprecation")
	private void setUpNotification() {
		notification = new Notification(iconId, "正在下载："+fileName, System.currentTimeMillis());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent();
		PendingIntent pi = PendingIntent.getActivity(UpdateNotifyService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification_for_downloadservice_view);
		rv.setTextViewText(R.id.update_text,"准备下载");
		rv.setImageViewResource(R.id.update_img, iconId);
		notification.contentView = rv;
		notification.contentIntent = pi;
		manager.notify(iconId, notification);
	}
	
	private void sendLoadedState() {
		if (isDownloaded(size)) {
			installApk();
		}
	};
	
	private void installApk() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.parse("file://"+downLoadPath), "application/vnd.android.package-archive");
		startActivity(intent);
	}
	
	private boolean isDownloaded(long size) {
		File file = new File(downLoadPath);
		if (file.exists()) {
			if(file.length() == size)
				return true;
			else{
				file.delete();
				return false;
			}
		}
		return false;
	}
	
	private void disableSSLCertificateChecking() {
	    TrustManager[] trustAllCerts = new TrustManager[] {
	        new X509TrustManager() {

	            @Override
	            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
	                // not implemented
	            }

	            @Override
	            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
	                // not implemented
	            }

	            @Override
	            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
	                return null;
	            }

	        }
	    };

	    try {

	        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					// TODO Auto-generated method stub
					return true;
				}

	        });
	        SSLContext sc = SSLContext.getInstance("TLS");
	        sc.init(null, trustAllCerts, new java.security.SecureRandom());
	        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

	    } catch (KeyManagementException e) {
	        e.printStackTrace();
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	}
}